<script setup lang="ts">
import { onMounted, ref, computed } from 'vue'
import { useRoute } from 'vue-router'
import { getOrderDetail, getOrderLogs } from '@/api/order/admin'
import { OrderGoods, OrderItem, OrderLog } from '@/api/order/types'
import { orderStatusMap } from '@/constants/order'
import { ContentWrap } from '@/components/ContentWrap'
import UpdateOrderStatus from './components/UpdateOrderStatus.vue'
import UpdateOrderAmount from './components/UpdateOrderAmount.vue'

const route = useRoute()
const orderNo = route.query.orderNo || route.params.orderNo

const orderInfo = ref<OrderItem>()
const orderGoodsList = ref<OrderGoods[]>()
const orderLogList = ref<OrderLog>()

const updateStatusDialogVisible = ref(false)
const updateAmountDialogVisible = ref(false)

const orderStatusLabel = computed(() => orderStatusMap[orderInfo.value?.orderStatus] ?? '未知')

// 统一获取订单详情和日志的方法
const fetchOrderDetailAndLogs = async () => {
  try {
    const res = await getOrderDetail(orderNo)
    console.log('订单详情:', res)
    if (res && res.data) {
      orderInfo.value = res.data.orderInfo
      orderGoodsList.value = res.data.orderGoodsList
    } else {
      console.error('订单详情 返回数据格式不正确:', res)
    }

    // 获取订单日志
    const logRes = await getOrderLogs(orderNo)
    if (logRes && logRes.data) {
      orderLogList.value = logRes.data
    } else {
      console.error('订单日志 返回数据格式不正确:', res)
    }
  } catch (error) {
    console.error('获取接口失败:', error)
  }
}

onMounted(async () => {
  await fetchOrderDetailAndLogs()
})

// 处理状态更新成功事件
const handleUpdateSuccess = () => {
  // 重新加载订单详情和日志
  fetchOrderDetailAndLogs()
}

// 刷新订单详情（保持向后兼容）
const refreshOrderDetail = fetchOrderDetailAndLogs
</script>

<template>
  <ContentWrap title="订单详情" message="展示订单明细，商品，日志等">
    <!-- 订单基本信息 -->
    <div class="title">订单信息</div>
    <el-descriptions :column="2" border>
      <el-descriptions-item label="订单编号">{{ orderInfo?.orderNo }}</el-descriptions-item>
      <el-descriptions-item label="订单状态">
        <div style="display: flex; justify-content: space-between; width: 100%">
          <span>{{ orderStatusLabel }}</span>
          <el-button type="primary" link @click="updateStatusDialogVisible = true">
            修改订单状态
          </el-button>
        </div>
      </el-descriptions-item>
      <el-descriptions-item label="用户 ID">{{ orderInfo?.userId }}</el-descriptions-item>
      <el-descriptions-item label="订单金额">
        <div style="display: flex; justify-content: space-between; width: 100%">
          <span>¥{{ orderInfo?.payAmount }}</span>
          <el-button type="primary" link @click="updateAmountDialogVisible = true">
            修改订单金额
          </el-button>
        </div>
      </el-descriptions-item>
      <el-descriptions-item label="创建时间">{{ orderInfo?.createdAt }}</el-descriptions-item>
      <el-descriptions-item label="更新时间">{{ orderInfo?.updatedAt }}</el-descriptions-item>
      <el-descriptions-item label="备注" :span="2">{{
        orderInfo?.remark || '暂无'
      }}</el-descriptions-item>
    </el-descriptions>

    <!-- 商品列表（表格） -->
    <div class="title">商品信息</div>
    <el-table :data="orderGoodsList" border stripe size="small">
      <el-table-column prop="skuId" label="skuId" width="100" />
      <el-table-column prop="skuCode" label="skuCode" width="120" />
      <el-table-column label="主图" width="180">
        <template #default="{ row }">
          <el-image
            :src="row.mainImg"
            class="product-image"
            fit="cover"
            preview-teleported
            :preview-src-list="[row.mainImg]"
          >
            <template v-slot:error>
              <div class="product-image">
                <el-icon :size="20"><Picture /></el-icon>
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="商品标题" min-width="200" show-overflow-tooltip />
      <el-table-column prop="price" label="价格" width="100" align="center" />
      <el-table-column prop="qty" label="数量" width="80" align="center" />
      <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip>
        <template #default="{ row }">
          {{ row.remark || '-' }}
        </template>
      </el-table-column>
    </el-table>

    <!-- 订单日志列表 -->
    <div class="title">订单日志</div>
    <el-table
      :data="orderLogList"
      border
      stripe
      size="small"
      v-if="orderLogList && orderLogList.length > 0"
    >
      <el-table-column prop="content" label="日志内容" min-width="300" show-overflow-tooltip />
      <el-table-column prop="createdAt" label="创建时间" width="200" />
    </el-table>
    <div v-else class="no-data">暂无日志记录</div>
    <!-- 底部按钮 -->
    <div class="footer-btn">
      <el-button @click="$router.back()">返回</el-button>
    </div>
  </ContentWrap>

  <!-- 修改订单状态弹窗 -->
  <UpdateOrderStatus
    v-if="orderInfo"
    v-model:visible="updateStatusDialogVisible"
    :order-no="orderInfo.orderNo"
    :current-status="orderInfo.orderStatus"
    @success="handleUpdateSuccess"
  />

  <!-- 修改订单金额弹窗 -->
  <UpdateOrderAmount
    v-if="orderInfo"
    v-model:visible="updateAmountDialogVisible"
    :order-no="orderInfo.orderNo"
    :current-amount="orderInfo.payAmount"
    @success="handleUpdateSuccess"
  />
</template>

<style scoped>
.title {
  margin: 24px 0 12px 0;
  font-size: 15px;
  font-weight: 600;
}
.footer-btn {
  margin-top: 16px;
  text-align: right;
}
/* 新增的product-image类 */
.product-image {
  width: 50px;
  height: 50px;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s ease;
  display: flex;
  justify-content: center;
  align-items: center;
}

.product-image:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.no-data {
  text-align: center;
  color: #909399;
  padding: 20px 0;
}
</style>
